<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/adapter.js"></script>

<script type="text/javascript">
var pc_constraints = {
  'optional': [
    {'DtlsSrtpKeyAgreement': true},
    {'RtpDataChannels': false},
	{'iceTransports': 'udp'}
  ]};
  
 var offerOptions = {
  offerToReceiveAudio: 0,
  offerToReceiveVideo: 1
};

 var media_constraints = {
    audio: false,
    video: true
}; 
  
// Set up audio and video regardless of what devices are present.
var sdpConstraints = {'mandatory': {
  'OfferToReceiveAudio':false,
  'OfferToReceiveVideo':true }};
  
var constraints = {video: true};  

var count = 0;
var ws;
var pc;
var servers = null;
 
function handleIceCandidate(event) {
  console.log('handleIceCandidate event: ', event);
  if(event.candidate) {
	console.log(parseCandidate(event.candidate.candidate));
  }
    console.log("ice gathering state " + pc.iceGatheringState);
  if(pc.iceGatheringState == "complete") {
    console.log("Sending offer SDP.");
	ws.send(pc.localDescription.sdp);
  }
}

function handleSignalingStateChange(event) {
	console.log('handleSignalingStateChange ' + pc.signalingState + '. Event: ', event);
}

function setLocalSDP(sessionDescription) {
  pc.setLocalDescription(sessionDescription, localDescriptionSuccess, showError); 
}

function localDescriptionSuccess(event) {
console.log("Local description successfully set. " + event);
}

function remoteDescriptionSuccess(event) {
console.log("Remote description successfully set. " + event);
pc.createAnswer(setLocalSDP, showError, sdpConstraints);
}

function answerCreated(sessionDescription) {
  pc.setLocalDescription(sessionDescription, null, showError);
}

function handleRemoteStreamAdded(event) {
  console.log('Remote stream added.');
  
  //if(document.querySelector("#remoteVideo").src != null) {
//	console.log("Removing existing stream.");
  //	document.querySelector("#remoteVideo").pause();
	//document.querySelector("#remoteVideo").src = null;
  //}
  //document.querySelector("#remoteVideo").src = //URL.createObjectURL(event.stream);
  attachMediaStream(document.querySelector("#remoteVideo"), event.stream);
  document.querySelector("#remoteVideo").play();
}

function handleRemoteStreamRemoved(event) {
  console.log('Remote stream removed. Event: ', event);
}

function handleIceStateChange(event) {
  console.log('ICE state changed, connection state ' + pc.iceConnectionState + ', gathering state ' + pc.iceGatheringState + '. Event: ', event);
}

function showError(error)
{
	console.log("ERROR: " + error);
}

function parseCandidate(text) {
  var candidateStr = "candidate:";
  var pos = text.indexOf(candidateStr) + candidateStr.length;
  var fields = text.substr(pos).split(" ");
  return {
    "component": fields[1],
    "type": fields[7],
    "foundation": fields[0],
    "protocol": fields[2],
    "address": fields[4],
    "port": fields[5],
    "priority": fields[3]
  };
}

function wsConnect() {

	//if(pc != null) {
	//	console.log("Closing peer connection.");
	//	pc.close();
	//}

			pc = new RTCPeerConnection(null, pc_constraints);
		//pc = new webkitRTCPeerConnection(null, pc_constraints);
		pc.onicecandidate = handleIceCandidate;
		pc.onaddstream = handleRemoteStreamAdded;
		pc.onremovestream = handleRemoteStreamRemoved;
		pc.onsignalingstatechange = handleSignalingStateChange;
		pc.oniceconnectionstatechange = handleIceStateChange;
	
	getUserMedia(media_constraints, attachMediaSuccessCallback, attachMediaErrorCallback);
	
     //src = null;
	//ws = new WebSocket("wss://192.168.33.116:8081/stream?path=0.hivpx");
	//if(count % 2 == 0) {
	//	src = "wss://192.168.33.128:8081/stream?path=0.lovpx";
	//}
	//else {
	//	src = "wss://192.168.33.128:8081/stream?path=0.hivpx";
	//}
	//console.log("Web socket source: " + src + ".");
	//ws = new WebSocket(src)
	
	count++;
};

// Attach media handlers and setters.

function attachMediaSuccessCallback(stream) {
  console.log("Attach media success callback.");
  //window.stream = stream; // make stream available to console
  
   var videoTracks = stream.getVideoTracks();
  console.log('Using video device: ' + videoTracks[0].label);
  
  pc.addStream(stream);
  
  attachMediaStream(document.querySelector('#localVideo'), stream);
  
  //pc.createOffer(setLocalSDP, onCreateSessionDescriptionError, offerOptions);
  
    //ws = new WebSocket("ws://192.168.33.117:8081/stream?path=0.hivpx");
	ws = new WebSocket("wss://aaron-pc.q.in:8081/stream?path=0.hivpx");

	ws.onopen = function () {
		console.log("web socket onopen.");
	};
		
	ws.onmessage = function (evt) {
		console.log("web socket onmessage: " + evt.data + ".");
		pc.setRemoteDescription(new RTCSessionDescription({type: "offer", sdp: evt.data}), remoteDescriptionSuccess, showError);
	};
	
	ws.onclose = function () {
		console.log("web socket closed.");
	};
}

function attachMediaErrorCallback(error) {
  console.log('Error attaching media: ', error);
}	

function onCreateSessionDescriptionError(error) {
  trace('Failed to create session description: ' + error.toString());
}

function onCreateOfferSuccess(desc) {
  trace('Offer from pc\n' + desc.sdp);
  trace('pc setLocalDescription start');
  pc.setLocalDescription(desc, function() {
    onSetLocalSuccess(pc);
  }, onSetSessionDescriptionError);
}

function onSetLocalSuccess(pc) {
  trace(' setLocalDescription complete');
}

function onSetRemoteSuccess(pc) {
  trace(' setRemoteDescription complete');
  pc.createAnswer(onCreateAnswerSuccess, onCreateSessionDescriptionError);
}

function onCreateAnswerSuccess(desc) {
  trace('Answer from pc:\n' + desc.sdp);
  trace('pc setLocalDescription start');
  pc.setLocalDescription(desc, function() {
    onSetLocalSuccess(pc);
  }, onSetSessionDescriptionError);
}


function onSetSessionDescriptionError(error) {
  trace('Failed to set session description: ' + error.toString());
}
	
function onIceCandidate(pc, event) {
  if (event.candidate) {
    pc.addIceCandidate(new RTCIceCandidate(event.candidate),
        function() {
          onAddIceCandidateSuccess(pc);
        },
        function(err) {
          onAddIceCandidateError(pc, err);
        }
    );
    trace(' ICE candidate: \n' + event.candidate.candidate);
  }
}

function onAddIceCandidateSuccess(pc) {
  trace(' addIceCandidate success ' + pc.iceGatheringState);
  
	if(pc.iceGatheringState == "complete") {
    console.log("Sending offer SDP.");
	//ws.send(pc.localDescription.sdp);
	trace(pc.localDescription.sdp);
  }
}

function onAddIceCandidateError(pc, error) {
  trace(' failed to add ICE Candidate: ' + error.toString());
}

function onIceStateChange(pc, event) {
	trace(' ICE state change ', event);
  if (pc) {
    trace(' ICE state: ' + pc.iceConnectionState);
    console.log('ICE state change event: ', event);
  }
}
	
 </script>
  
     <div>
    <button style="width: 300px; height: 200px;" onclick="wsConnect();">Click here to start</button>
	</div>
  
 <video controls autoplay='true' id="localVideo">
 </video>
  
  <video controls autoplay='true' id="remoteVideo">
 </video>

 
